import React, {useCallback, useEffect, useState} from 'react';
import {
    Alert,
    Button,
    Card,
    Col,
    Form,
    InputNumber,
    message,
    Modal,
    Progress,
    Row,
    Select,
    Space,
    Statistic,
    Steps,
    Table,
    Typography,
    Upload
} from 'antd';
import {
    CheckCircleOutlined,
    CloudUploadOutlined,
    InboxOutlined,
    PlayCircleOutlined,
    ReloadOutlined
} from '@ant-design/icons';
import {algorithmAPI, uploadDataAPI} from '../../services/api';
import './DataUploadPage.css';

const {Dragger} = Upload;
const {Title, Text, Paragraph} = Typography;
const {Step} = Steps;
const {Option} = Select;

const DataUploadPage = () => {
    const [form] = Form.useForm();
    const [currentStep, setCurrentStep] = useState(0);
    const [batchId, setBatchId] = useState(null);
    const [batchInfo, setBatchInfo] = useState(null);
    const [routesFile, setRoutesFile] = useState(null);
    const [shipmentsFile, setShipmentsFile] = useState(null);
    const [uploading, setUploading] = useState(false);
    const [executing, setExecuting] = useState(false);
    const [uploadProgress, setUploadProgress] = useState({routes: 0, shipments: 0});
    const [executionProgress, setExecutionProgress] = useState(0);
    const [executionStatus, setExecutionStatus] = useState('');
    const [taskId, setTaskId] = useState(null);
    const [batchList, setBatchList] = useState([]);
    const [batchStats, setBatchStats] = useState(null);
    const [showBatchList, setShowBatchList] = useState(false);

    // 加载批次列表
    const loadBatchList = useCallback(async () => {
        try {
            const response = await uploadDataAPI.getBatchList();
            // response已经是data部分，包含Page对象
            setBatchList(response.records || []);
        } catch (error) {
            console.error('加载批次列表失败:', error);
        }
    }, []);

    // 组件加载时获取批次列表
    useEffect(() => {
        loadBatchList();
    }, [loadBatchList]);

    // 创建批次
    const handleCreateBatch = useCallback(async (values) => {
        try {
            const response = await uploadDataAPI.createBatch(
                values.description,
                values.governmentSubsidy,
                values.timeValue
            );

            // response已经是data部分
            setBatchId(response.batchId);
            setBatchInfo(response.uploadBatch);
            setCurrentStep(1);
            message.success(`批次创建成功！批次ID: ${response.batchId}`);
        } catch (error) {
            message.error(`创建批次失败：${error.message || '未知错误'}`);
        }
    }, []);

    // 文件上传配置
    const uploadProps = (fileType, setFile, setProgress) => ({
        name: 'file',
        multiple: false,
        accept: '.csv',
        beforeUpload: (file) => {
            const isCSV = file.type === 'text/csv' || file.name.endsWith('.csv');
            if (!isCSV) {
                message.error('只能上传CSV文件!');
                return false;
            }
            const isLt10M = file.size / 1024 / 1024 < 10;
            if (!isLt10M) {
                message.error('文件大小不能超过10MB!');
                return false;
            }

            const fileName = file.name.toLowerCase();
            if (fileType === 'route' && !fileName.includes('route')) {
                message.error('路线数据文件名必须包含"route"字样!');
                return false;
            }
            if (fileType === 'shipment' && !fileName.includes('shipment')) {
                message.error('货物数据文件名必须包含"shipment"字样!');
                return false;
            }

            setFile(file);
            return false;
        },
        onRemove: () => {
            setFile(null);
            setProgress(0);
        },
        fileList: [],
        showUploadList: false
    });

    // 上传路线文件
    const handleUploadRoutes = useCallback(async () => {
        if (!routesFile) {
            message.warning('请先选择路线文件');
            return;
        }

        setUploading(true);
        setUploadProgress(prev => ({...prev, routes: 0}));

        const progressInterval = setInterval(() => {
            setUploadProgress(prev => ({
                ...prev,
                routes: Math.min(prev.routes + 10, 90)
            }));
        }, 200);

        try {
            await uploadDataAPI.uploadRouteCsv(routesFile, batchId);
            clearInterval(progressInterval);
            setUploadProgress(prev => ({...prev, routes: 100}));
            setRoutesFile(null);
            message.success('路线文件上传成功！');
            setCurrentStep(2);
        } catch (error) {
            clearInterval(progressInterval);
            message.error(`路线文件上传失败：${error.message || '未知错误'}`);
        } finally {
            setUploading(false);
            setTimeout(() => {
                setUploadProgress(prev => ({...prev, routes: 0}));
            }, 2000);
        }
    }, [routesFile, batchId]);

    // 上传货物文件
    const handleUploadShipments = useCallback(async () => {
        if (!shipmentsFile) {
            message.warning('请先选择货物文件');
            return;
        }

        setUploading(true);
        setUploadProgress(prev => ({...prev, shipments: 0}));

        const progressInterval = setInterval(() => {
            setUploadProgress(prev => ({
                ...prev,
                shipments: Math.min(prev.shipments + 10, 90)
            }));
        }, 200);

        try {
            await uploadDataAPI.uploadShipmentCsv(shipmentsFile, batchId);
            clearInterval(progressInterval);
            setUploadProgress(prev => ({...prev, shipments: 100}));
            setShipmentsFile(null);
            message.success('货物文件上传成功！');
            setCurrentStep(3);
        } catch (error) {
            clearInterval(progressInterval);
            message.error(`货物文件上传失败：${error.message || '未知错误'}`);
        } finally {
            setUploading(false);
            setTimeout(() => {
                setUploadProgress(prev => ({...prev, shipments: 0}));
            }, 2000);
        }
    }, [shipmentsFile, batchId]);

    // 执行算法
    const handleExecuteAlgorithm = useCallback(async () => {
        if (!batchId) {
            message.warning('请先上传数据文件');
            return;
        }

        setExecuting(true);
        setExecutionProgress(0);
        setExecutionStatus('正在启动算法...');

        try {
            // 使用异步执行
            const response = await algorithmAPI.executeAsync(batchId);
            const taskIdMatch = response.message.match(/任务ID: (.+)/);
            const currentTaskId = taskIdMatch ? taskIdMatch[1] : null;

            if (currentTaskId) {
                setTaskId(currentTaskId);
                setCurrentStep(4);

                // 订阅任务状态
                const eventSource = algorithmAPI.subscribeToTaskStatus(currentTaskId);
                setExecutionStatus('正在执行算法...');

                eventSource.onmessage = (event) => {
                    try {
                        const data = JSON.parse(event.data);
                        if (data.progress !== undefined) {
                            setExecutionProgress(data.progress);
                        }
                        if (data.status) {
                            setExecutionStatus(data.status);
                        }
                        if (data.stage) {
                            setExecutionStatus(`${data.stage}: ${data.message || ''}`);
                        }

                        if (data.status === 'SUCCESS' || data.status === 'FAILED') {
                            setExecuting(false);
                            eventSource.close();
                            if (data.status === 'SUCCESS') {
                                setCurrentStep(5);
                                message.success('算法执行成功！匹配结果已生成');
                                // 加载批次统计信息
                                loadBatchStats();
                            } else {
                                message.error(`算法执行失败：${data.message || '未知错误'}`);
                            }
                        }
                    } catch (e) {
                        console.error('解析SSE数据失败:', e);
                    }
                };

                eventSource.onerror = (error) => {
                    console.error('SSE连接错误:', error);
                    setExecuting(false);
                    eventSource.close();
                };
            }
        } catch (error) {
            setExecuting(false);
            message.error(`算法执行失败：${error.message || '未知错误'}`);
        }
    }, [batchId]);

    // 加载批次统计信息
    const loadBatchStats = useCallback(async () => {
        if (!batchId) return;
        try {
            const response = await uploadDataAPI.getBatchStats(batchId);
            // response已经是data部分
            setBatchStats(response);
        } catch (error) {
            console.error('加载批次统计失败:', error);
        }
    }, [batchId]);

    // 重置流程
    const handleReset = useCallback(() => {
        setCurrentStep(0);
        setBatchId(null);
        setBatchInfo(null);
        setRoutesFile(null);
        setShipmentsFile(null);
        setExecutionProgress(0);
        setExecutionStatus('');
        setTaskId(null);
        setBatchStats(null);
        form.resetFields();
    }, [form]);

    // 查看批次列表
    const columns = [
        {
            title: '批次ID',
            dataIndex: 'dataId',
            key: 'dataId',
        },
        {
            title: '描述',
            dataIndex: 'description',
            key: 'description',
        },
        {
            title: '政府补贴',
            dataIndex: 'governmentSubsidy',
            key: 'governmentSubsidy',
            render: (value) => value ? `${value}%` : '-',
        },
        {
            title: '时间价值',
            dataIndex: 'timeValue',
            key: 'timeValue',
            render: (value) => value ? `${value}%` : '-',
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render: (time) => time ? new Date(time).toLocaleString() : '-',
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            render: (time) => time ? new Date(time).toLocaleString() : '-',
        },
    ];

    return (
        <div className="data-upload-page">
            <div className="page-header">
                <Title level={2}>数据上传与算法执行</Title>
                <Paragraph type="secondary">
                    按照步骤创建批次、上传数据文件、执行匹配算法生成最优路线规划
                </Paragraph>
                <Button
                    type="link"
                    icon={<ReloadOutlined/>}
                    onClick={() => setShowBatchList(true)}
                    style={{padding: 0}}
                >
                    查看历史批次
                </Button>
            </div>

            <Card>
                <Steps current={currentStep} style={{marginBottom: 32}}>
                    <Step title="创建批次" description="设置批次参数"/>
                    <Step title="上传路线" description="上传路线CSV文件"/>
                    <Step title="上传货物" description="上传货物CSV文件"/>
                    <Step title="执行算法" description="运行匹配算法"/>
                    <Step title="完成" description="查看结果"/>
                </Steps>

                <div className="step-content">
                    {currentStep === 0 && (
                        <Form
                            form={form}
                            layout="vertical"
                            onFinish={handleCreateBatch}
                        >
                            <Form.Item
                                label="批次描述"
                                name="description"
                            >
                                <InputNumber
                                    placeholder="请输入批次描述（可选）"
                                    style={{width: '100%'}}
                                />
                            </Form.Item>

                            <Form.Item
                                label="政府补贴（%）"
                                name="governmentSubsidy"
                                rules={[
                                    {type: 'number', min: 0, max: 100, message: '请输入0-100之间的数值'}
                                ]}
                            >
                                <InputNumber
                                    placeholder="请输入政府补贴百分比（0-100，可选）"
                                    min={0}
                                    max={100}
                                    style={{width: '100%'}}
                                />
                            </Form.Item>

                            <Form.Item
                                label="时间价值（%）"
                                name="timeValue"
                                rules={[
                                    {type: 'number', min: 0, max: 100, message: '请输入0-100之间的数值'}
                                ]}
                            >
                                <InputNumber
                                    placeholder="请输入时间价值百分比（0-100，可选）"
                                    min={0}
                                    max={100}
                                    style={{width: '100%'}}
                                />
                            </Form.Item>

                            <Form.Item>
                                <Space>
                                    <Button type="primary" htmlType="submit" icon={<CloudUploadOutlined/>}>
                                        创建批次
                                    </Button>
                                    <Button onClick={handleReset}>
                                        重置
                                    </Button>
                                </Space>
                            </Form.Item>
                        </Form>
                    )}

                    {currentStep === 1 && batchId && (
                        <div>
                            <Alert
                                message={`批次创建成功！批次ID: ${batchId}`}
                                description="请上传路线数据文件（route.csv）"
                                type="success"
                                showIcon
                                style={{marginBottom: 24}}
                            />
                            <Dragger
                                {...uploadProps('route', setRoutesFile, (progress) => setUploadProgress(prev => ({
                                    ...prev,
                                    routes: progress
                                })))}
                                className="file-dragger"
                            >
                                <p className="ant-upload-drag-icon">
                                    {routesFile ? <CheckCircleOutlined style={{color: '#52c41a'}}/> :
                                        <InboxOutlined/>}
                                </p>
                                <p className="ant-upload-text">
                                    {routesFile ? routesFile.name : '点击或拖拽上传路线数据文件'}
                                </p>
                                <p className="ant-upload-hint">
                                    支持 CSV 格式，文件大小不超过10MB<br/>
                                    文件名必须包含"route"字样
                                </p>
                            </Dragger>
                            {routesFile && (
                                <Button
                                    type="primary"
                                    style={{marginTop: 16}}
                                    onClick={handleUploadRoutes}
                                    loading={uploading}
                                    icon={<CloudUploadOutlined/>}
                                >
                                    上传路线文件
                                </Button>
                            )}
                            {uploadProgress.routes > 0 && uploading && (
                                <Progress
                                    percent={uploadProgress.routes}
                                    status={uploadProgress.routes === 100 ? "success" : "active"}
                                    style={{marginTop: 16}}
                                />
                            )}
                        </div>
                    )}

                    {currentStep === 2 && (
                        <div>
                            <Alert
                                message="路线文件上传成功！"
                                description="请上传货物数据文件（shipment.csv）"
                                type="success"
                                showIcon
                                style={{marginBottom: 24}}
                            />
                            <Dragger
                                {...uploadProps('shipment', setShipmentsFile, (progress) => setUploadProgress(prev => ({
                                    ...prev,
                                    shipments: progress
                                })))}
                                className="file-dragger"
                            >
                                <p className="ant-upload-drag-icon">
                                    {shipmentsFile ? <CheckCircleOutlined style={{color: '#52c41a'}}/> :
                                        <InboxOutlined/>}
                                </p>
                                <p className="ant-upload-text">
                                    {shipmentsFile ? shipmentsFile.name : '点击或拖拽上传货物数据文件'}
                                </p>
                                <p className="ant-upload-hint">
                                    支持 CSV 格式，文件大小不超过10MB<br/>
                                    文件名必须包含"shipment"字样
                                </p>
                            </Dragger>
                            {shipmentsFile && (
                                <Button
                                    type="primary"
                                    style={{marginTop: 16}}
                                    onClick={handleUploadShipments}
                                    loading={uploading}
                                    icon={<CloudUploadOutlined/>}
                                >
                                    上传货物文件
                                </Button>
                            )}
                            {uploadProgress.shipments > 0 && uploading && (
                                <Progress
                                    percent={uploadProgress.shipments}
                                    status={uploadProgress.shipments === 100 ? "success" : "active"}
                                    style={{marginTop: 16}}
                                />
                            )}
                        </div>
                    )}

                    {currentStep === 3 && (
                        <div>
                            <Alert
                                message="数据文件上传完成！"
                                description="点击下方按钮开始执行匹配算法"
                                type="success"
                                showIcon
                                style={{marginBottom: 24}}
                            />
                            <div style={{textAlign: 'center'}}>
                                <Button
                                    type="primary"
                                    size="large"
                                    onClick={handleExecuteAlgorithm}
                                    loading={executing}
                                    icon={<PlayCircleOutlined/>}
                                >
                                    执行匹配算法
                                </Button>
                            </div>
                        </div>
                    )}

                    {(currentStep === 4 || executing) && (
                        <div>
                            <div style={{textAlign: 'center', marginBottom: 24}}>
                                <Title level={4}>算法执行中...</Title>
                                <Text type="secondary">任务ID: {taskId}</Text>
                            </div>
                            <Progress
                                percent={executionProgress}
                                status="active"
                                strokeColor={{
                                    '0%': '#108ee9',
                                    '100%': '#87d068',
                                }}
                            />
                            <div style={{marginTop: 16, textAlign: 'center'}}>
                                <Text>{executionStatus}</Text>
                            </div>
                        </div>
                    )}

                    {currentStep === 5 && batchStats && (
                        <div>
                            <Alert
                                message="算法执行完成！"
                                description="匹配结果已生成，以下是本次执行的统计信息"
                                type="success"
                                showIcon
                                style={{marginBottom: 24}}
                            />
                            <Row gutter={16} style={{marginBottom: 24}}>
                                <Col span={6}>
                                    <Statistic title="路线数量" value={batchStats.routeCount || 0}/>
                                </Col>
                                <Col span={6}>
                                    <Statistic title="货物数量" value={batchStats.shipmentCount || 0}/>
                                </Col>
                                <Col span={6}>
                                    <Statistic title="匹配数量" value={batchStats.matchedCount || 0}/>
                                </Col>
                                <Col span={6}>
                                    <Statistic title="匹配成功率" value={batchStats.matchRate || 0} suffix="%"/>
                                </Col>
                            </Row>
                            <div style={{textAlign: 'center'}}>
                                <Space>
                                    <Button type="primary" onClick={() => window.location.href = '/matching'}>
                                        查看匹配结果
                                    </Button>
                                    <Button onClick={handleReset}>
                                        创建新批次
                                    </Button>
                                </Space>
                            </div>
                        </div>
                    )}
                </div>
            </Card>

            <Modal
                title="批次列表"
                open={showBatchList}
                onCancel={() => setShowBatchList(false)}
                footer={null}
                width={1000}
            >
                <Table
                    dataSource={batchList}
                    columns={columns}
                    rowKey="dataId"
                    pagination={{pageSize: 10}}
                />
            </Modal>
        </div>
    );
};

export default DataUploadPage;